/**
 * Created by Blink on 2017/8/21.
 * watch code for debug component
 * when any file updated. will copy to demo modules.
 */

const watch = require('watch');
const demoPath = './__test__/BlinkDemo/node_modules/react-native-blink-ui';
const fs = require('fs');
const Path = require('path');

function checkPath(path) {
    const arr = path.split(/[\/\\]/);

    return new Promise((res, rej) => {
        const fn = (p, i) => {
            if (i === arr.length - 1) {
                res(p);
                return;
            }

            if (p === '.' || p === '') {
                fn(p + '/' + arr[i + 1], i + 1);
            } else {
                fs.stat(p, (err, stat) => {
                    if (err) {
                        fs.mkdir(p, (err) => {
                            console.log('create dir:' + p);
                            if (err) rej(err);
                            else {
                                fn(p + '/' + arr[i + 1], i + 1);
                            }
                        })
                    } else {
                        fn(p + '/' + arr[i + 1], i + 1);
                    }
                })
            }
        };

        fn(arr[0], 0)
    });
}

watch.createMonitor('./src', (monitor) => {
    monitor.on("created", (f, stat) => {
        readFile(f).then((data) => {
            const path = demoPath + '/' + f;

            checkPath(path).then(() => {
                fs.open(path, 'w+', (err, fd) => {
                    if (err) console.error(err);
                    else {
                        fs.write(fd, data, 0, data.length, 0, () => {
                            console.log("create file:" + path);
                            fs.close(fd);
                        })
                    }
                })
            }).catch((e) => console.error(e));

        }).catch((err) => {
            console.error(err);
        })
    });

    monitor.on("changed", (f, stat) => {
        readFile(f).then((data) => {
            const path = demoPath + '\\' + f;

            fs.open(path, 'w+', (err, fd) => {
                if (err) console.error(err);
                else {
                    fs.write(fd, data, 0, data.length, 0, () => {
                        console.log("change file:" + path);
                        fs.close(fd);
                    })
                }
            })

        }).catch((err) => {
            console.error(err);
        })
    });

    monitor.on("removed", (f, stat) => {
        const path = demoPath + '\\' + f;

        fs.unlink(path, (err) => {
            if (err) console.error(err);
            else console.log('remove file:' + path)
        })
    });

    console.log("watch file.");
});

function readFile(path) {
    return new Promise((res, rej) => {
        fs.readFile(path, (err, data) => {
            if (err) rej(err);
            else res(data);
        })
    })
}